//
//  SCAudioMediaPlayerView.m
//  Pods
//
//  Created by Chao Sheng on 2021/12/20.
//

#import "SCAudioMediaPlayerView.h"
#import "SCAudioMediaPlayer.h"

#define sc_W(a) (sc_PAD ? ([UIScreen mainScreen].bounds.size.width / 375.0 * a * 0.7) : ([UIScreen mainScreen].bounds.size.width / 375.0 * a))

#define sc_rgba(r, g, b, a) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]

@interface SCAudioMediaSlider : UISlider

@end

@implementation SCAudioMediaSlider

 //控制slider的高
- (CGRect)trackRectForBounds:(CGRect)bounds {

    bounds.size.height = sc_W(4);
    bounds.origin.y = (sc_W(30)-sc_W(4))/2;
    self.layer.cornerRadius = sc_W(2);
    self.layer.masksToBounds = true;
    
    return bounds;
}

@end

@interface SCAudioMediaPlayerView ()

@property (nonatomic, strong) UIView *controlView;

@property (nonatomic, strong) SCAudioMediaSlider *slider;

@property (nonatomic, strong) UIProgressView *progressView;

@property (nonatomic, strong) UIProgressView *bufferProgressView;

@property (nonatomic, strong) UIButton *playBtn;

@property (nonatomic, strong) UIImageView *playImageView;

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UILabel *timeLabel;

@property (nonatomic, assign) SCAudioMediaControlType type;

@property (nonatomic, strong) SCAudioMediaPlayer *player;

@property (nonatomic, copy) NSString *audioURL;

@property (nonatomic, copy) NSString *quesTitle;

@property (nonatomic, assign) CGFloat totalTime;

@property (nonatomic, assign) CGFloat currentTime;

@property (nonatomic, assign) CGFloat bufferTime;

@property (nonatomic, assign) CGFloat oldTime;

@property (nonatomic, assign) SCAudioMediaState state;


@end

@implementation SCAudioMediaPlayerView

- (void)dealloc {
    NSLog(@"播放器销毁");
    [NSNotificationCenter.defaultCenter removeObserver:self];
}

- (instancetype)initWithControlType:(SCAudioMediaControlType)type QuesAudio:(nonnull NSString *)auidoURL QuesTitle:(nonnull NSString *)title AddAudioInitNotification:(nonnull void (^)(id obj))addAudioNotification{
    
    if (self = [super init]) {
        self.type = type;
        self.audioURL = auidoURL;
        self.quesTitle = title;
        [self setupUI];
        [self initPlayer];
        
        addAudioNotification(self);
        
//      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onChildAudioPlayBegin:) name:KZNotiName_onChildAudioPlayBegin object:nil];

    }
    return self;
}

#pragma mark - noti
- (void)onChildAudioPlayBegin:(NSNotification *)noti {
//    if (noti.object == _model) {
//        [self pause];
//    }
}
#pragma mark - view
- (void)setupUI {
    [self addSubview:self.controlView];
    [self.controlView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.left.right.top.bottom.equalTo(@0);
        make.height.equalTo(@(sc_W(70)));
    }];
    
    [self addSubview:self.playBtn];
    [self.playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self);
        make.left.equalTo(@(sc_W(20)));
        make.width.height.equalTo(@(sc_W(50)));
    }];
    
    [self addSubview:self.playImageView];
    [self.playImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self);
        make.left.equalTo(@(sc_W(20)));
        make.width.height.equalTo(@(sc_W(50)));
    }];
    
    [self addSubview:self.bufferProgressView];
    [self.bufferProgressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.playBtn.mas_right).offset(sc_W(10));
        make.width.equalTo(@(sc_W(250)));
        make.centerY.equalTo(self);
        make.height.equalTo(@(sc_W(4)));
    }];
    
    
    if (self.type==SCAudioMediaControlExam) { //考试
        
        [self addSubview:self.titleLabel];
        self.titleLabel.text = self.quesTitle;
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.bufferProgressView);
            make.bottom.equalTo(self.bufferProgressView.mas_top).offset(sc_W(-4));
        }];

        [self addSubview:self.progressView];
        [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.bufferProgressView);
            make.left.right.equalTo(self.bufferProgressView);
            make.height.equalTo(@(sc_W(4)));
        }];
        
    } else { //练习
        
        [self.bufferProgressView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self).offset(sc_W(-5));
        }];
        
        [self addSubview:self.slider];
        [self.slider mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.bufferProgressView);
            make.left.right.equalTo(self.bufferProgressView);
            make.height.equalTo(@(sc_W(30)));
        }];
    }
    
    [self addSubview:self.timeLabel];
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.bufferProgressView);
        make.top.equalTo(self.bufferProgressView.mas_bottom).offset(sc_W(5));
    }];
}

- (void)initPlayer {
    
    sc_weak(self);
    self.player = [[SCAudioMediaPlayer alloc] initWithRate:1];
    [self.player setScAudioBufferCallBack:^(SCAudioMediaBufferState bufferState, CGFloat bufferTime, CGFloat totalTime) {
       
        weakself.timeLabel.text = [NSString stringWithFormat:@"%02li:%02li/%02li:%02li",(NSInteger)weakself.currentTime/60,(NSInteger)weakself.currentTime%60, (NSInteger)weakself.totalTime / 60, (NSInteger)weakself.totalTime % 60];
        if(totalTime>0) {
            weakself.bufferProgressView.progress = (float)(bufferTime / totalTime);
            weakself.totalTime = totalTime;
            weakself.bufferTime = bufferTime;
        }
        //NSLog(@"bufferState:%@==%.2f/%.2f",@(bufferState),bufferTime,self.totalTime);
    }];
    [self.player setScAudioUpdateTimeCallBack:^(SCAudioMediaState state, CGFloat currentTime, CGFloat totalTime) {
        
        weakself.timeLabel.text = [NSString stringWithFormat:@"%02li:%02li/%02li:%02li",(NSInteger)weakself.currentTime/60,(NSInteger)weakself.currentTime%60, (NSInteger)weakself.totalTime / 60, (NSInteger)weakself.totalTime % 60];
        
        if(totalTime>0) {
            if (weakself.type == SCAudioMediaControlExam) {
                //NSLog(@"%f",currentTime/totalTime);
                weakself.progressView.progress = (float)(currentTime / totalTime);
            } else {
                weakself.slider.value = (float)(currentTime / totalTime);
            }
            
            weakself.totalTime = totalTime;
            weakself.currentTime = currentTime;
            weakself.oldTime = weakself.currentTime;
            weakself.state = state;
        }
    }];
    
//    // 直接获取时长
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        AVURLAsset*audioAsset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:[self.model.QuesAudio.Path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]] options:nil];
//        CMTime audioDuration = audioAsset.duration;
//        float audioDurationSeconds = CMTimeGetSeconds(audioDuration);
//        dispatch_async(dispatch_get_main_queue(), ^{
//            self.currentTime = 0;
//            self.totalTime = audioDurationSeconds;
//            self.timeLabel.text = [NSString stringWithFormat:@"%02li:%02li/%02li:%02li",(NSInteger)self.currentTime/60,(NSInteger)self.currentTime%60, (NSInteger)self.totalTime / 60, (NSInteger)self.totalTime % 60];
//        });
//    });
    
    
}

#pragma mark - Method
- (void)playAction:(UIButton*)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self play];
    } else {
        [self pause];
    }
}

- (void)onSliderValueChange:(id)sender {
    if(self.state==SCAudioMediaStatePlaying) {
        [self.player pause];
    }
    
    UISlider *slider = (UISlider*)sender;
    
    _currentTime = floor(slider.value * _totalTime);
    
    _timeLabel.text = [NSString stringWithFormat:@"%02li:%02li/%02li:%02li",(NSInteger)_currentTime / 60,(NSInteger)_currentTime % 60, (NSInteger)_totalTime / 60, (NSInteger)_totalTime % 60];
}

- (void)onSliderValueEnd:(id)sender {
    //偏移量过小不执行
    if(fabs(self.currentTime-self.oldTime) < 0.5) {
        return;
    }
    self.oldTime = self.currentTime;
    
    [self.player seekTime:_currentTime];
}

- (void)setState:(SCAudioMediaState)state {
    _state = state;
    if (state==SCAudioMediaStatePlaying) {
        if (self.type == SCAudioMediaControlExam) {
            [self.playImageView startAnimating];
        } else {
            self.playBtn.selected = true;
        }
    } else {
        if (self.type == SCAudioMediaControlExam) {
            [self.playImageView stopAnimating];
        } else {
            self.playBtn.selected = false;
        }
    }
    
    if (state==SCAudioMediaStateEnd || state==SCAudioMediaStateFail) {
        if (self.type == SCAudioMediaControlExam) {
            self.progressView.progress = 0;
        } else {
            self.slider.value = 0;
        }
        
        _currentTime = 0;
        _timeLabel.text = [NSString stringWithFormat:@"%02li:%02li/%02li:%02li",(NSInteger)_currentTime / 60,(NSInteger)_currentTime % 60, (NSInteger)_totalTime / 60, (NSInteger)_totalTime % 60];
    }
}

#pragma mark - Public
- (void)pause {
    [self.player pause];
}

- (void)play {
    [self.player play];
   // [[NSNotificationCenter defaultCenter] postNotificationName:KZNotiName_onAudioPlayBegin object:_model];
}

- (void)startInitAudioData {
    self.player.audioUrl = self.audioURL;
}

#pragma mark - 懒加载
- (UIView *)controlView {
    if (!_controlView) {
        _controlView  = [[UIView alloc] init];
        _controlView.backgroundColor = UIColor.whiteColor;
        _controlView.layer.cornerRadius = sc_W(8);
        _controlView.layer.masksToBounds = true;
    }
    return _controlView;
}

- (UIButton *)playBtn {
    if (!_playBtn) {
        _playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_playBtn setBackgroundImage:[UIImage sc_bundleImageNamed:@"LGQ-音频播放"] forState:UIControlStateNormal];
        [_playBtn setBackgroundImage:[UIImage sc_bundleImageNamed:@"LGQ-音频暂停"] forState:UIControlStateSelected];
        [_playBtn addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
        if (self.type == SCAudioMediaControlExam) {
            _playBtn.hidden = true;
        } else {
            _playBtn.hidden = false;
        }
    }
    return _playBtn;
}

- (UIProgressView *)bufferProgressView {
    if (!_bufferProgressView) {
        _bufferProgressView = [[UIProgressView alloc] init];
        _bufferProgressView.progressTintColor = sc_rgba(217, 217, 217, 1);
        _bufferProgressView.trackTintColor = sc_rgba(237, 237, 237, 1);
        _bufferProgressView.layer.cornerRadius = sc_W(2);
        _bufferProgressView.layer.masksToBounds = true;
    }
    return _bufferProgressView;
}

- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] init];
        _progressView.progressTintColor = sc_rgba(11, 175, 251, 1);
        _progressView.trackTintColor = [UIColor clearColor];
        _progressView.layer.cornerRadius = sc_W(2);
        _progressView.layer.masksToBounds = true;
    }
    return _progressView;
}

- (UISlider *)slider {
    if (!_slider) {
        _slider = [[SCAudioMediaSlider alloc] init];
        _slider.minimumTrackTintColor = sc_rgba(11, 175, 251, 1);;
        _slider.maximumTrackTintColor = UIColor.clearColor;
        [_slider setThumbImage:[UIImage sc_bundleImageNamed:@"LGQ-音频播放器滑块@2x"] forState:UIControlStateNormal];
        [_slider addTarget:self action:@selector(onSliderValueChange:) forControlEvents:UIControlEventValueChanged];
        [_slider addTarget:self action:@selector(onSliderValueEnd:) forControlEvents:UIControlEventTouchUpInside];
        [_slider addTarget:self action:@selector(onSliderValueEnd:) forControlEvents:UIControlEventTouchUpOutside];
    }
    return _slider;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.font =[UIFont fontWithName:@"PingFangSC-Medium" size:sc_PAD?18:14];
        _titleLabel.textColor = UIColor.blackColor;
    }
    return _titleLabel;
}

- (UILabel *)timeLabel {
    if (!_timeLabel) {
        _timeLabel = [[UILabel alloc] init];
        _timeLabel.font = [UIFont systemFontOfSize:sc_PAD?16:12];
        _timeLabel.textColor = sc_rgba(142, 142, 142, 1);
        _timeLabel.text = @"--/--";
    }
    return _timeLabel;
}

- (UIImageView *)playImageView {
    if (!_playImageView) {
        _playImageView = [[UIImageView alloc] init];
        NSArray *images = @[[UIImage sc_bundleImageNamed:@"LGQ-喇叭播放-1"],[UIImage sc_bundleImageNamed:@"LGQ-喇叭播放-2"],[UIImage sc_bundleImageNamed:@"LGQ-喇叭播放-3"]];
        _playImageView.animationImages = images;
        _playImageView.animationDuration = 0.8;
        _playImageView.image = [UIImage sc_bundleImageNamed:@"LGQ-喇叭播放-3"];
        if (self.type == SCAudioMediaControlExam) {
            _playImageView.hidden = false;
        } else {
            _playImageView.hidden = true;
        }
    }
    return _playImageView;
}


@end
